package com.zzy.ware.service.impl;

import com.zzy.utils.utils.R;
import com.zzy.ware.feign.ProductFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.utils.utils.PageUtils;
import com.zzy.utils.utils.Query;

import com.zzy.ware.mapper.WareSkuMapper;
import com.zzy.ware.entity.WareSkuEntity;
import com.zzy.ware.service.WareSkuService;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuMapper, WareSkuEntity> implements WareSkuService {
	
	@Autowired
	private WareSkuMapper wareSkuMapper;
	
	@Autowired
	private ProductFeignService productFeignService;
	
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		/**
		 * skuId: 1
		 * wareId: 2
		 */
		QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
		String skuId = (String) params.get("skuId");
		if (!StringUtils.isEmpty(skuId)) {
			wrapper.eq("sku_id", skuId);
		}
		String wareId = (String) params.get("wareId");
		if (!StringUtils.isEmpty(wareId)) {
			wrapper.eq("ware_id", wareId);
		}
		IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), wrapper);
		
		return new PageUtils(page);
	}
	
	@Override
	public void addStock(Long skuId, Long wareId, Integer skuNum) {
		/*判断如果没有这个库存记录新增*/
		List<WareSkuEntity> entities = wareSkuMapper.selectList(new QueryWrapper<WareSkuEntity>()
				.eq("sku_id", skuId)
				.eq("ware_id", wareId));
		if (entities == null || entities.size() == 0) {
			WareSkuEntity skuEntity = new WareSkuEntity();
			skuEntity.setSkuId(skuId);
			skuEntity.setStock(skuNum);
			skuEntity.setWareId(wareId);
			skuEntity.setStockLocked(0);
			/*
			  TODO:远程查询sku的name
			  如果失败，整个事务无需回滚
			  		1、自己catch异常
			  		2、TODO：还可以用什么办法，让异常出现以后不回滚
			 */
			try {
				R info = productFeignService.info(skuId);
				Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
				if (info.getCode() == 0) {
					skuEntity.setSkuName((String) data.get("skuName"));
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			
			wareSkuMapper.insert(skuEntity);
		}
		wareSkuMapper.addStock(skuId, wareId, skuNum);
	}
	
}















